<?php

namespace app\api\controller;

use think\Controller;
use app\common\model\GiftOrder;
use app\common\model\Remittance as RemittanceModel;
use think\Db;

class Remittance extends Controller
{

    /**
     * 创建订单
     */
    public static function createOrder($sn, $user_id, $price)
    {
        $order_number = createOrderNumber();
        $withdrawal_money = $price;
        $tax_rate_money = 0;
        $arrival_amount = bcsub(bcsub($withdrawal_money, $tax_rate_money, 2), 0, 2);
        // 获取提现银行卡
        $bank_card = Db::name("bank_card")->where('status', 1)->where('sale_id', $user_id)->find();
        // 验证订单
        $count = RemittanceModel::where('order_number', $order_number)->where('status', 1)->count();
        if ($count > 0) {
            return ["code" => 0, "msg" => "存在相同订单"];
        }
        $tax_rate_money = bcmul($withdrawal_money, 0, 2);
        $data = [
            "order_number" => $order_number,
            "user_id" => $user_id,
            "sn" => $sn,
            "withdrawal_money" => $withdrawal_money,
            "service_charge" => 0,
            "tax_rate" => 0,
            "tax_rate_money" => $tax_rate_money,
            "arrival_amount" => $arrival_amount,
            "name" => $bank_card["name"],
            "phone" => $bank_card["phone"],
            "idcards" => $bank_card["idcards"],
            "bank_card_number" => $bank_card["bank_card_number"],
            "create_time" => time()
        ];
        $res = RemittanceModel::create($data);
        if ($res) {
            return ["code" => 1, "msg" => "订单创建成功", "order_num" => $order_number];
        } else {
            return ["code" => 0, "msg" => "订单创建失败"];
        }
    }

    /**
     * 订单作废
     */
    public static function ordervoid($order_number, $msg)
    {
        $order = RemittanceModel::where('order_number', $order_number)->find();
        if (!empty($order)) {
            if ($order->status == 1 && $order->payment_status == 1) {
                $res = RemittanceModel::where('order_number', $order_number)->update(["status" => 2, "port_content" => $msg]);
            }
        }
    }

    /**
     * 打款
     */
    public function remit($orderno)
    {
        $return = Yunhuotec::remittance($orderno);
        if ($return["code"] != 200) {
            self::ordervoid($orderno, $return["msg"]);
            $this->error($return["msg"]);
            $this->success($return["msg"]);
        } else {
            $this->success("提现成功！");
        }
    }
}